package com.lanzhou.yuanfen.sys.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lanzhou.yuanfen.sys.entity.Visitor;
import com.lanzhou.yuanfen.sys.mapper.VisitorMapper;
import com.lanzhou.yuanfen.sys.service.IVisitorService;
import com.lanzhou.yuanfen.util.DateUtil;
import com.lanzhou.yuanfen.vo.CountWeekDTO;
import com.lanzhou.yuanfen.vo.WebSiteUV;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lcllge
 * @since 2019-12-02
 */
@Service
@CacheConfig(cacheNames = "visitor", keyGenerator = "myKeyGenerator")
public class VisitorServiceImpl extends ServiceImpl<VisitorMapper, Visitor> implements IVisitorService {

    @Resource
    private VisitorMapper visitorMapper;

    @Override
    @Cacheable(value = "week")
    public WebSiteUV recentWeekUV() {
        return obtainWeekUV();
    }

    @Override
    @CachePut(value = "week")
    public WebSiteUV reWriteWeekUV() {
        return obtainWeekUV();
    }

    private WebSiteUV obtainWeekUV() {
        String[] weekParam = DateUtil.getWeekParam();
        List<String> weekStr = DateUtil.getWeekStr();
        List<CountWeekDTO> countWeeks = visitorMapper.countWeek(weekParam[1], weekParam[0]);
        WebSiteUV uv = new WebSiteUV();
        uv.setX(weekStr);
        setYData(weekStr, countWeeks, uv);
        return uv;
    }

    /**
     * 配置Y轴数据
     *
     * @param weekStr
     * @param countWeeks
     * @param uv
     */
    private void setYData(List<String> weekStr, List<CountWeekDTO> countWeeks, WebSiteUV uv) {
        Map<String, CountWeekDTO> weekDTOMap = new HashMap<>();
        if (countWeeks.size() != 0) {
            weekDTOMap = countWeeks.stream().collect(Collectors.toMap(CountWeekDTO::getVisitDate, x -> x));
        }
        List<Integer> idNus = new ArrayList<>();
        List<Integer> thumbs = new ArrayList<>();
        for (String day : weekStr) {
            CountWeekDTO countWeekDTO = weekDTOMap.get(day);
            if (countWeekDTO == null) {
                idNus.add(0);
                thumbs.add(0);
            } else {
                idNus.add(countWeekDTO.getIdNu());
                thumbs.add(countWeekDTO.getThumb());
            }
        }
        Map<String, List<Integer>> uvY = new HashMap<>();
        uvY.put("访客人数", idNus);
        uvY.put("点赞数", thumbs);
        uv.setY(uvY);
    }


}
